<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kea2 Test Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2ecc71;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --dark-color: #2c3e50;
            --light-color: #ecf0f1;
        }
        
        body {
            font-family: 'Segoe UI', Roboto, -apple-system, sans-serif;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }
        
        /* Custom container width - wider than Bootstrap default */
        .container {
            max-width: 98% !important;
            width: 98% !important;
        }
        
        @media (min-width: 1200px) {
            .container {
                max-width: 1800px !important;
                width: 95% !important;
            }
        }
        
        @media (min-width: 1400px) {
            .container {
                max-width: 2000px !important;
                width: 92% !important;
            }
        }
        
        @media (min-width: 1600px) {
            .container {
                max-width: 2200px !important;
                width: 90% !important;
            }
        }
        
        @media (min-width: 1800px) {
            .container {
                max-width: 2400px !important;
                width: 88% !important;
            }
        }
        
        @media (min-width: 2000px) {
            .container {
                max-width: 2600px !important;
                width: 85% !important;
            }
        }
        
        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 2.5rem 0;
            margin-bottom: 3rem;
            border-radius: 0 0 20px 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .stats-card {
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            height: 100%;
            overflow: hidden;
            padding: 1rem;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            font-weight: 600;
            padding: 1.25rem 1.5rem;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        .screenshots-container {
            display: flex;
            overflow-x: auto;
            gap: 15px;
            padding: 15px 0;
            scrollbar-width: thin;
            scrollbar-color: var(--primary-color) #eee;
        }
        
        .screenshots-container::-webkit-scrollbar {
            height: 8px;
        }
        
        .screenshots-container::-webkit-scrollbar-track {
            background: #eee;
            border-radius: 10px;
        }
        
        .screenshots-container::-webkit-scrollbar-thumb {
            background-color: var(--primary-color);
            border-radius: 10px;
        }
        
        .screenshot-item {
            flex: 0 0 auto;
            width: 300px;
            position: relative;
            transition: transform 0.2s;
            margin-bottom: 10px;
        }
        
        .screenshot-item:hover {
            transform: scale(1.03);
        }
        
        .screenshot-img {
            width: 300px;
            height: 400px;
            object-fit: contain;
            border-radius: 8px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 8px;
        }
        
        .screenshot-caption {
            font-size: 13px;
            color: #555;
            padding: 12px 8px;
            font-weight: 500;
            text-align: center;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
            line-height: 1.5;
            white-space: normal;
            word-wrap: break-word;
            min-height: 50px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        .screenshot-caption .step-number {
            display: block;
            font-weight: 600;
            color: var(--primary-color);
            font-size: 12px;
            margin-bottom: 4px;
        }
        
        .screenshot-caption .step-action {
            display: block;
            font-size: 13px;
            color: #666;
            font-weight: 400;
            line-height: 1.3;
        }
        
        .table-custom {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            width: 100%;
            table-layout: auto;
        }

        .crash-analysis-panel {
            background-color: #ffffff;
            border-radius: 14px;
            padding: 1.75rem;
            box-shadow: 0 6px 15px rgba(44, 62, 80, 0.08);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .crash-analysis-panel .btn-group .btn {
            font-weight: 600;
        }
        
        .table-custom thead {
            background-color: #495057;
            color: white;
        }
        
        .table-custom th {
            font-weight: 600;
            padding: 15px 12px;
            white-space: nowrap;
            text-align: center;
        }
        
        .table-custom td {
            padding: 15px 12px;
            vertical-align: middle;
            text-align: center;
        }

        /* Override text alignment for stack trace containers */
        .table-custom td .bg-light {
            text-align: left;
        }

        .table-custom td .bg-light pre {
            text-align: left !important;
        }

        /* Enhanced Error Details styling for Property Statistics */
        .table-custom tr.collapse {
            position: relative;
            z-index: 10;
        }

        .table-custom tr.collapse td {
            border-top: none;
            padding-top: 0;
        }

        .table-custom tr.collapse .bg-light {
            max-width: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border: 1px solid #e9ecef;
        }

        .table-custom tr.collapse pre {
            font-size: 0.85rem;
            line-height: 1.4;
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 0.75rem;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .table-custom tr.collapse details {
            margin-top: 0.5rem;
        }

        .table-custom tr.collapse summary {
            cursor: pointer;
            margin-bottom: 0.5rem;
        }
        
        /* Specific column widths for property statistics table */
        .table-custom th:nth-child(1), .table-custom td:nth-child(1) { /* Index */
            width: 5%;
            min-width: 50px;
        }

        .table-custom th:nth-child(2), .table-custom td:nth-child(2) { /* Property Name */
            width: 18%;
            min-width: 180px;
            text-align: left;
        }

        .table-custom th:nth-child(3), .table-custom td:nth-child(3) { /* Precondition Satisfied */
            width: 9%;
            min-width: 85px;
        }

        .table-custom th:nth-child(4), .table-custom td:nth-child(4) { /* Executed */
            width: 8%;
            min-width: 70px;
        }

        .table-custom th:nth-child(5), .table-custom td:nth-child(5) { /* Fails */
            width: 7%;
            min-width: 65px;
        }

        .table-custom th:nth-child(6), .table-custom td:nth-child(6) { /* Errors */
            width: 8%;
            min-width: 70px;
        }

        .table-custom th:nth-child(7), .table-custom td:nth-child(7) { /* Error Details */
            width: 45%;
            min-width: 400px;
            text-align: center;
            position: relative;
        }

        /* Property Checking Statistics specific adjustments */
        .table-property-stats th,
        .table-property-stats td {
            padding: 20px 14px;
            line-height: 1.65;
        }

        .table-property-stats th:nth-child(1),
        .table-property-stats td:nth-child(1) {
            width: 6%;
            min-width: 60px;
        }

        .table-property-stats th:nth-child(2),
        .table-property-stats td:nth-child(2) {
            width: 22%;
            min-width: 200px;
            text-align: left;
        }

        .table-property-stats th:nth-child(3),
        .table-property-stats td:nth-child(3) {
            width: 10%;
            min-width: 90px;
        }

        .table-property-stats th:nth-child(4),
        .table-property-stats td:nth-child(4) {
            width: 9%;
            min-width: 80px;
        }

        .table-property-stats th:nth-child(5),
        .table-property-stats td:nth-child(5) {
            width: 9%;
            min-width: 80px;
        }

        .table-property-stats th:nth-child(6),
        .table-property-stats td:nth-child(6) {
            width: 9%;
            min-width: 80px;
        }

        .table-property-stats th:nth-child(7),
        .table-property-stats td:nth-child(7) {
            width: 9%;
            min-width: 80px;
        }

        .table-property-stats th:nth-child(8),
        .table-property-stats td:nth-child(8) {
            width: 26%;
            min-width: 260px;
            text-align: left;
        }

        .table-property-stats td:nth-child(8) {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 0.75rem;
        }
        
        .table-custom tbody tr:nth-of-type(odd) {
            background-color: rgba(0, 0, 0, 0.02);
        }
        
        .table-custom tbody tr:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }
        
        .stat-value {
            font-size: 2.2rem;
            font-weight: 700;
            display: block;
            margin-bottom: 0.8rem;
            line-height: 1.2;
        }
        
        .stat-label {
            font-size: 1rem;
            color: #666;
            display: block;
            margin-top: 5px;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 24px;
        }

        .summary-item {
            text-align: center;
            padding: 20px 16px;
            border-radius: 12px;
            background-color: #f8fafc;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .summary-item:hover {
            transform: translateY(-4px);
            box-shadow: 0 6px 12px rgba(15, 23, 42, 0.08);
        }

        .summary-item i {
            font-size: 2rem;
            display: block;
            margin-bottom: 12px;
        }
        
        .chart-container {
            background-color: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            margin-bottom: 40px;
        }
        
        .section-title {
            position: relative;
            padding-bottom: 15px;
            margin-bottom: 30px;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        .section-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            height: 3px;
            width: 50px;
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            border-radius: 3px;
        }
        
        .section-block {
            margin-bottom: 70px;
        }
        
        .value-highlight {
            color: var(--primary-color);
        }
        
        .value-danger {
            color: var(--danger-color);
        }
        
        .value-warning {
            color: var(--warning-color);
        }
        
        .value-success {
            color: var(--secondary-color);
        }
        
        .summary-card {
            border-radius: 12px;
            background-color: white;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            padding: 30px;
            margin-bottom: 40px;
        }
        
        .link-button {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.2s;
        }
        
        .link-button:hover {
            color: var(--secondary-color);
            text-decoration: underline;
        }
        
        .badge-custom {
            padding: 6px 12px;
            border-radius: 50px;
            font-weight: 500;
            font-size: 0.9rem;
            margin: 0 2px;
        }
        
        .activity-list {
            height: 550px;
            overflow-y: auto;
            border-radius: 8px;
            border: 1px solid rgba(0,0,0,0.1);
            padding: 15px;
            background-color: rgba(255,255,255,0.5);
            scrollbar-width: thin;
            scrollbar-color: var(--primary-color) #eee;
            margin-bottom: 15px;
        }
        
        .activity-list::-webkit-scrollbar {
            width: 8px;
        }
        
        .activity-list::-webkit-scrollbar-track {
            background: #eee;
            border-radius: 10px;
        }
        
        .activity-list::-webkit-scrollbar-thumb {
            background-color: var(--primary-color);
            border-radius: 10px;
        }
        
        .activities-container {
            display: flex;
            flex-direction: column;
            height: 650px;
        }
        
        .pagination-container {
            padding: 10px 0;
            background-color: white;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .activity-item {
            padding: 10px 15px;
            border-radius: 6px;
            margin-bottom: 10px;
            font-size: 0.95rem;
            word-break: break-all;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            transition: all 0.2s;
            line-height: 1.5;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .activity-item .activity-content {
            display: flex;
            align-items: center;
            flex: 1;
            min-width: 0;
        }
        
        .activity-item .activity-name {
            flex: 1;
            word-break: break-all;
            margin-right: 10px;
        }
        
        .activity-item .traversal-badge {
            flex-shrink: 0;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .activity-item:hover {
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transform: translateX(3px);
        }
        
        .nav-tabs .nav-link {
            color: #666;
            border: 1px solid transparent;
            border-radius: 6px 6px 0 0;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .nav-tabs .nav-link:hover {
            color: var(--primary-color);
            border-color: rgba(52, 152, 219, 0.2);
            background-color: rgba(52, 152, 219, 0.05);
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background-color: white;
            border-color: #dee2e6 #dee2e6 #fff;
            font-weight: 600;
        }
        
        .tab-content {
            border: 1px solid #dee2e6;
            border-top: none;
            border-radius: 0 0 8px 8px;
            padding: 20px;
            background-color: #fafafa;
        }
        
        .sorting-controls {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .sorting-controls .form-select {
            min-width: 140px;
        }
        
        .sorting-controls .btn {
            transition: all 0.3s ease;
        }
        
        .sorting-controls .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .sort-icon {
            margin-left: 8px;
            transition: all 0.3s ease;
            font-size: 1.4rem;
            color: #ffffff !important;
            opacity: 0.6;
            text-shadow: 0 0 3px rgba(0,0,0,0.3);
        }
        
        .sort-icon:hover {
            opacity: 1;
            transform: scale(1.2);
            text-shadow: 0 0 5px rgba(0,0,0,0.5);
        }
        
        .sort-icon.active {
            opacity: 1;
            font-weight: bold;
            text-shadow: 0 0 5px rgba(0,0,0,0.5);
        }
        
        .sort-icon.asc.active {
            color: #40e0d0 !important;
        }
        
        .sort-icon.desc.active {
            color: #ff6b6b !important;
        }
        
        .table-violations thead {
            background-color: #dc3545 !important;
            color: white;
        }
        
        .table-violations .sort-icon {
            color: #ffffff !important;
            text-shadow: 0 0 3px rgba(0,0,0,0.4);
        }
        
        .table-violations .sort-icon:hover {
            opacity: 1;
            transform: scale(1.2);
            text-shadow: 0 0 5px rgba(0,0,0,0.6);
        }

        /* Specific column widths for property violations table */
        .table-violations th:nth-child(1), .table-violations td:nth-child(1) { /* Index */
            width: 10%;
            min-width: 60px;
            text-align: center;
        }

        .table-violations th:nth-child(2), .table-violations td:nth-child(2) { /* Property Name */
            width: 40%;
            min-width: 200px;
            text-align: left;
        }

        .table-violations th:nth-child(3), .table-violations td:nth-child(3) { /* Interaction Scenario Pages */
            width: 50%;
            min-width: 150px;
            text-align: center;
        }
        
        @media (max-width: 768px) {
            .container {
                max-width: 98% !important;
                width: 98% !important;
                padding-left: 10px !important;
                padding-right: 10px !important;
            }
            
            .stat-value {
                font-size: 1.5rem;
            }
            
            .screenshot-item {
                width: 280px;
            }
            
            .screenshot-img {
                width: 280px;
                height: 400px;
            }
            
            .table-custom {
                font-size: 0.9rem;
            }
            
            .table-custom th, .table-custom td {
                padding: 10px 6px;
            }
            
            .badge-custom {
                font-size: 0.8rem;
                padding: 4px 8px;
            }
        }
        
        @media (max-width: 576px) {
            .container {
                max-width: 100% !important;
                width: 100% !important;
                padding-left: 5px !important;
                padding-right: 5px !important;
            }
            
            .screenshot-item {
                width: 260px;
            }
            
            .screenshot-img {
                width: 260px;
                height: 380px;
            }
            
            .table-custom {
                font-size: 0.8rem;
            }
            
            .table-custom th, .table-custom td {
                padding: 8px 4px;
                white-space: normal;
            }
        }
        
        /* Modern Sorting Controls Styling */
        .sorting-controls-modern {
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 16px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
            transition: all 0.2s ease;
            position: relative;
        }

        .sorting-controls-modern:hover {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);
            border-color: #d1d5db;
        }
        
        .sort-label-section {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        
        .sort-icon-wrapper {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #3498db, #2980b9);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(52, 152, 219, 0.3);
        }
        
        .sort-icon-wrapper i {
            color: white;
            font-size: 20px;
        }
        
        .sort-text {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        
        .sort-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            line-height: 1.2;
        }
        
        .sort-subtitle {
            font-size: 13px;
            color: #7f8c8d;
            font-weight: 400;
            line-height: 1.2;
        }
        
        .sort-button-section {
            display: flex;
            align-items: center;
        }
        
        .btn-sort-modern {
            background: linear-gradient(135deg, #27ae60, #2ecc71);
            border: none;
            border-radius: 10px;
            padding: 12px 20px;
            color: white;
            font-weight: 500;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(46, 204, 113, 0.3);
            position: relative;
            overflow: hidden;
        }

        .btn-sort-modern::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .btn-sort-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(46, 204, 113, 0.4);
        }

        .btn-sort-modern:hover::before {
            left: 100%;
        }

        .btn-sort-modern:active {
            transform: translateY(0px);
            box-shadow: 0 2px 8px rgba(46, 204, 113, 0.3);
        }
        
        .btn-content {
            display: flex;
            align-items: center;
            gap: 8px;
            position: relative;
            z-index: 1;
        }
        
        .btn-icon {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .btn-text {
            font-size: 14px;
            font-weight: 500;
            white-space: nowrap;
        }
        
        .btn-arrow {
            font-size: 14px;
            transition: transform 0.3s ease;
            opacity: 0.8;
        }
        
        .btn-sort-modern:hover .btn-arrow {
            transform: scale(1.1);
            opacity: 1;
        }
        
        /* Responsive design for sorting controls */
        @media (max-width: 768px) {
            .sorting-controls-modern {
                padding: 16px 20px;
            }
            
            .sort-label-section {
                gap: 12px;
            }
            
            .sort-icon-wrapper {
                width: 40px;
                height: 40px;
            }
            
            .sort-icon-wrapper i {
                font-size: 16px;
            }
            
            .sort-title {
                font-size: 14px;
            }
            
            .sort-subtitle {
                font-size: 12px;
            }
            
            .btn-sort-modern {
                padding: 10px 16px;
            }
            
            .btn-text {
                font-size: 13px;
            }
        }
        
        @media (max-width: 576px) {
            .sorting-controls-modern {
                flex-direction: column;
                text-align: center;
                gap: 16px;
            }
            
            .sorting-controls-modern .d-flex {
                flex-direction: column;
                gap: 16px;
            }
            
            .sort-label-section {
                justify-content: center;
            }
        }
        
        /* Search Controls Styling */
        .search-controls-modern {
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
            transition: all 0.2s ease;
            position: relative;
        }

        .search-controls-modern:hover {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);
            border-color: #d1d5db;
        }

        /* Property search container with outline */
        .property-search-container {
            position: relative;
            display: flex;
            align-items: center;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background-color: #f8f9fa;
            transition: all 0.2s ease;
            overflow: hidden;
        }

        .property-search-container:hover {
            border-color: #9ca3af;
        }

        .property-search-container:focus-within {
            border-color: #3b82f6;
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
            background-color: #ffffff;
        }

        /* Simple search input styling for Property Statistics */
        .property-stats-search-simple {
            border: none !important;
            box-shadow: none !important;
            background-color: transparent !important;
            border-radius: 0 !important;
            padding: 8px 12px !important;
            font-size: 14px;
            flex: 1;
            outline: none;
        }

        .property-stats-search-simple:focus {
            background-color: transparent !important;
            box-shadow: none !important;
            border: none !important;
            outline: none;
        }

        .property-stats-search-simple::placeholder {
            color: #9ca3af;
            font-style: italic;
        }

        /* Search icon button */
        .property-search-icon-btn {
            background: none;
            border: none;
            padding: 8px 12px;
            color: #6b7280;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.2s ease;
            border-left: 1px solid #e5e7eb;
        }

        .property-search-icon-btn:hover {
            color: #3b82f6;
            background-color: rgba(59, 130, 246, 0.05);
        }

        .property-search-icon-btn:active {
            color: #1d4ed8;
        }

        /* Activities Coverage table styling */
        .table-activities thead {
            background-color: #007bff !important;
            color: white;
        }

        .table-activities .sort-icon {
            color: #ffffff !important;
            text-shadow: 0 0 3px rgba(0,0,0,0.4);
        }

        .table-activities .sort-icon:hover {
            opacity: 1;
            transform: scale(1.2);
            text-shadow: 0 0 5px rgba(0,0,0,0.6);
        }

        .table-activities .activities-sort-icon {
            color: #ffffff !important;
            text-shadow: 0 0 3px rgba(0,0,0,0.4);
        }

        .table-activities .activities-sort-icon:hover {
            opacity: 1;
            transform: scale(1.2);
            text-shadow: 0 0 5px rgba(0,0,0,0.6);
        }

        /* Column widths for activities table */
        .table-activities th:nth-child(1), .table-activities td:nth-child(1) { /* Activity Name */
            width: 70%;
            min-width: 300px;
            text-align: left;
            padding-left: 180px;
        }

        .table-activities th:nth-child(2), .table-activities td:nth-child(2) { /* Visit Count */
            width: 30%;
            min-width: 150px;
            text-align: center;
        }

        /* Modern Activity Item Styling */
        .activity-item {
            background: #ffffff;
            border: 1px solid #f3f4f6;
            border-radius: 12px;
            padding: 16px 20px;
            margin-bottom: 8px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .activity-item:hover {
            border-color: #e5e7eb;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            transform: translateY(-1px);
        }

        .activity-content {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .activity-name {
            font-weight: 500;
            color: #374151;
            font-size: 14px;
        }

        .traversal-badge {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8) !important;
            border: none;
            border-radius: 20px;
            padding: 6px 12px;
            font-size: 12px;
            font-weight: 500;
            box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
        }

        /* Modern Search Input */
        .activity-search-input {
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.2s ease;
            background: #f9fafb;
        }

        .activity-search-input:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            background: #ffffff;
        }

        .search-btn {
            border-radius: 12px;
            padding: 12px 16px;
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            border: none;
            transition: all 0.2s ease;
        }

        .search-btn:hover {
            background: linear-gradient(135deg, #2563eb, #1e40af);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
        }

        /* Combined Search and Sort Controls */
        .search-sort-controls-modern {
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
            transition: all 0.2s ease;
            position: relative;
        }

        .search-sort-controls-modern:hover {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);
            border-color: #d1d5db;
        }

        .search-section {
            min-width: 0; /* Allow flex item to shrink */
        }

        .sort-section {
            flex-shrink: 0; /* Prevent sort section from shrinking */
        }

        .sort-label {
            white-space: nowrap;
            font-size: 14px;
        }

        /* Responsive design for combined controls */
        @media (max-width: 768px) {
            .search-sort-controls-modern .d-flex {
                flex-direction: column;
                gap: 16px !important;
            }

            .search-section {
                width: 100% !important;
                max-width: none !important;
                flex-shrink: 1 !important;
            }

            .sort-section {
                justify-content: center;
                width: 100%;
                margin-left: 0 !important;
            }
        }

        @media (max-width: 576px) {
            .search-section {
                max-width: none !important;
            }

            .search-icon-wrapper {
                width: 40px;
                height: 40px;
            }

            .search-icon-wrapper i {
                font-size: 18px;
            }
        }
        
        .search-icon-wrapper {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #17a2b8, #138496);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(23, 162, 184, 0.3);
        }
        
        .search-icon-wrapper i {
            color: white;
            font-size: 20px;
        }
        
        .activity-search-input {
            border: 1px solid #ced4da;
            border-radius: 8px 0 0 8px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .activity-search-input:focus {
            border-color: #17a2b8;
            box-shadow: 0 0 0 0.2rem rgba(23, 162, 184, 0.25);
        }
        
        .search-btn {
            border-radius: 0;
            border-left: none;
            border-right: none;
            padding: 12px 16px;
            transition: all 0.3s ease;
            background-color: #17a2b8;
            border-color: #17a2b8;
            color: white;
        }
        
        .search-btn:hover {
            background-color: #138496;
            border-color: #117a8b;
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .search-btn:focus {
            box-shadow: 0 0 0 0.2rem rgba(23, 162, 184, 0.5);
        }
        
        .search-clear-btn {
            border-radius: 0 8px 8px 0;
            border-left: none;
            padding: 12px 16px;
            transition: all 0.3s ease;
        }
        
        .search-clear-btn:hover {
            background-color: #dc3545;
            border-color: #dc3545;
            color: white;
        }
        
        .search-results-count {
            display: block;
            margin-top: 8px;
            font-size: 12px;
            font-style: italic;
        }
    </style>
</head>

<body>
    <!-- Header -->
    <header class="header text-center">
        <div class="container">
            <h1><i class="bi bi-bug"></i> Kea2 Test Report</h1>
            <p class="lead">Test Time: {{ test_time }}</p>
            <p class="lead">Log Stamp: {{ log_stamp }}</p>
        </div>
    </header>

    <div class="container mb-5">
        <!-- Test Summary -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="summary-card">
                    <h2 class="section-title">Test Summary</h2>
                    <div class="summary-grid">
                        <div class="summary-item">
                            <i class="bi bi-bug text-danger"></i>
                            <span class="stat-value value-danger">{{ bugs_found }}</span>
                            <span class="stat-label">Property Violations</span>
                        </div>
                        <div class="summary-item">
                            <i class="bi bi-clock-history text-primary"></i>
                            <span class="stat-value value-highlight">{{ total_testing_time }}</span>
                            <span class="stat-label">Total Testing Time</span>
                        </div>
                        <div class="summary-item">
                            <i class="bi bi-activity text-success"></i>
                            <span class="stat-value value-success">{{ executed_events }}</span>
                            <span class="stat-label">Executed Events</span>
                        </div>
                        <div class="summary-item">
                            <i class="bi bi-pie-chart text-warning"></i>
                            <span class="stat-value value-warning">{{ coverage_percent }}%</span>
                            <span class="stat-label">Activity Coverage</span>
                        </div>
                        <div class="summary-item">
                            <i class="bi bi-list-check text-info"></i>
                            <span class="stat-value value-highlight">{{ executed_properties_count }}/{{ all_properties_count }}</span>
                            <span class="stat-label">Executed Properties</span>
                        </div>
                        <div class="summary-item">
                            <i class="bi bi-exclamation-octagon text-danger"></i>
                            <span class="stat-value value-danger">{{ triggered_crash_count }}</span>
                            <span class="stat-label">Triggered Crash</span>
                        </div>
                        <div class="summary-item">
                            <i class="bi bi-hourglass-split text-warning"></i>
                            <span class="stat-value value-warning">{{ triggered_anr_count }}</span>
                            <span class="stat-label">Triggered ANR</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Coverage Trend Chart -->
        <div class="section-block">
            <h2 class="section-title">Coverage Trend</h2>
            <div class="chart-container">
                <canvas id="coverageChart"></canvas>
            </div>
        </div>

        <!-- Property Execution Trend Chart -->
        <div class="section-block">
            <h2 class="section-title">Property Execution Trend</h2>
            <div class="chart-container">
                <canvas id="propertyExecutionChart"></canvas>
            </div>
        </div>

        <!-- Activities Coverage -->
        <div class="section-block">
            <h2 class="section-title">Activities Coverage</h2>

            <!-- Search Controls for Activities -->
            <div class="mb-4">
                <div class="d-flex align-items-center">
                    <div style="width: 33%;">
                        <div class="property-search-container">
                            <input type="text" class="form-control property-search-input property-stats-search-simple"
                                   id="activities-search"
                                   placeholder="Search activities by name..."
                                   data-target="activities-container"
                                   data-item-class="activity-row"
                                   data-pagination="activities-pagination"
                                   data-page-size="activities-page-size">
                            <button class="property-search-icon-btn" type="button" id="activities-search-btn">
                                <i class="bi bi-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="ms-3">
                        <small class="text-muted search-results-count" id="activities-search-results"></small>
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-custom table-activities">
                    <thead>
                        <tr>
                            <th>Activity Name <span class="badge bg-primary ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ tested_activities_count }}/{{ total_activities_count }}</span></th>
                            <th>Visit Count <i class="bi bi-arrow-down-up text-muted sort-icon activities-sort-icon" id="visit-count-sort" data-column="visit-count" data-order="none" style="cursor: pointer;"></i></th>
                        </tr>
                    </thead>
                    <tbody id="activities-container">
                        {% if total_activities|length > 0 %}
                            {% for activity in total_activities %}
                            <tr class="activity-row" data-page="1"
                                data-activity-name="{{ activity }}"
                                data-visit-count="{{ activity_count_history[activity] if activity in activity_count_history else 0 }}">
                                <td>
                                    {% if activity in tested_activities %}
                                        <i class="bi bi-check-circle-fill text-success me-2"></i>
                                    {% else %}
                                        <i class="bi bi-dash-circle text-secondary me-2"></i>
                                    {% endif %}
                                    <span class="activity-name">{{ activity }}</span>
                                </td>
                                <td>
                                    {% if activity in activity_count_history %}
                                        <span class="badge bg-info text-white">
                                            <i class="bi bi-eye"></i> {{ activity_count_history[activity] }} times
                                        </span>
                                    {% else %}
                                        <span class="badge bg-secondary text-white">
                                            <i class="bi bi-dash"></i> 0 times
                                        </span>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        {% else %}
                            <tr>
                                <td colspan="2" class="text-center">
                                    <div class="alert alert-warning mb-0">
                                        No activities information available
                                    </div>
                                </td>
                            </tr>
                        {% endif %}
                    </tbody>
                </table>

                <!-- Pagination for Activities -->
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <div class="d-flex align-items-center">
                        <label for="activities-page-size" class="form-label me-2 mb-0">Show:</label>
                        <select class="form-select form-select-sm" id="activities-page-size" style="width: auto;">
                            <option value="5">5</option>
                            <option value="10" selected>10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                    <nav aria-label="Activities Pagination">
                        <ul class="pagination pagination-sm mb-0" id="activities-pagination">
                            <!-- Pagination will be generated by JavaScript -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>

        <!-- Screenshots Section -->
        {% if take_screenshots %}
        {% if screenshots %}
        <div class="section-block">
            <h2 class="section-title">Test Screenshots</h2>
            <div class="card">
                <div class="card-body">
                    <div class="screenshots-container" id="screenshots">
                        {% for screenshot in screenshots %}
                        <div class="screenshot-item">
                            <a href="{{ screenshot.path }}" target="_blank">
                                <img src="{{ screenshot.path }}" class="screenshot-img" id="{{ screenshot.id }}">
                            </a>
                            <div class="screenshot-caption">{{ screenshot.caption }}</div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
        {% else %}
        <div class="section-block">
            <h2 class="section-title">Test Screenshots</h2>
            <div class="alert alert-info text-center">
                <i class="bi bi-info-circle"></i> No screenshots captured in this test session.
            </div>
        </div>
        {% endif %}
        {% endif %}

        <!-- Crash Analysis Section -->
        {% if crash_events or anr_events %}
        <div class="section-block">
            <h2 class="section-title">
                <i class="bi bi-exclamation-triangle text-danger"></i> Crash and ANR Events
            </h2>
            
            <!-- Detailed Crash Information -->
            <div class="crash-analysis-panel">
                <!-- Event Filter -->
                <div class="mb-3">
                    <div class="btn-group" role="group" aria-label="Event filter">
                        <input type="radio" class="btn-check" name="event-filter" id="all-events" autocomplete="off" checked>
                        <label class="btn btn-outline-primary" for="all-events">All Events ({{ (crash_events|length) + (anr_events|length) }})</label>

                        <input type="radio" class="btn-check" name="event-filter" id="crashes-only" autocomplete="off">
                        <label class="btn btn-outline-danger" for="crashes-only">Crashes Only ({{ crash_events|length }})</label>

                        <input type="radio" class="btn-check" name="event-filter" id="anr-only" autocomplete="off">
                        <label class="btn btn-outline-warning" for="anr-only">ANR Only ({{ anr_events|length }})</label>
                    </div>
                </div>

                <!-- Events Table -->
                <div class="table-responsive">
                    <table class="table table-custom">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Time</th>
                                <th>Exception</th>
                                <th>Process</th>
                                {% if take_screenshots %}
                                <th>Interaction Scenario Pages</th>
                                {% endif %}
                                <th>Details</th>
                            </tr>
                        </thead>
                        <tbody id="crash-events-container">
                            {% for crash in crash_events %}
                            <tr class="event-row" data-type="crash" data-page="1">
                                <td><span class="badge bg-danger">CRASH</span></td>
                                <td>{{ crash.time }}</td>
                                <td>{{ crash.exception_type }}</td>
                                <td>{{ crash.process }}</td>
                                {% if take_screenshots %}
                                <td>
                                    {% if crash.screenshot_id %}
                                    <a href="#{{ crash.screenshot_id }}" class="link-button" onclick="scrollToScreenshot('{{ crash.screenshot_id }}')">
                                        <i class="bi bi-camera"></i> Screenshot {{ crash.screenshot_id }}
                                    </a>
                                    {% else %}
                                    <span class="text-muted">No screenshot</span>
                                    {% endif %}
                                </td>
                                {% endif %}
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" type="button"
                                            data-bs-toggle="collapse" data-bs-target="#crash-detail-{{ loop.index }}"
                                            aria-expanded="false" aria-controls="crash-detail-{{ loop.index }}">
                                        <i class="bi bi-eye"></i> Details
                                    </button>
                                    <button class="btn btn-sm btn-outline-secondary copy-stack-btn"
                                            data-stack-index="{{ loop.index }}">
                                        <i class="bi bi-clipboard"></i> Copy
                                    </button>
                                </td>
                            </tr>
                            <tr class="collapse" id="crash-detail-{{ loop.index }}">
                                <td colspan="{% if take_screenshots %}6{% else %}5{% endif %}">
                                    <div class="bg-light p-3 rounded">
                                        <h6 class="text-danger">Stack Trace:</h6>
                                        <pre class="text-danger mb-0 text-start" id="stack-trace-{{ loop.index }}" style="font-size: 0.9em; white-space: pre-wrap; text-align: left;">{{ crash.stack_trace }}</pre>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}

                            {% for anr in anr_events %}
                            <tr class="event-row" data-type="anr" data-page="1">
                                <td><span class="badge bg-warning text-dark">ANR</span></td>
                                <td>{{ anr.time }}</td>
                                <td>{{ anr.reason }}</td>
                                <td>{{ anr.process }}</td>
                                {% if take_screenshots %}
                                <td>
                                    {% if anr.screenshot_id %}
                                    <a href="#{{ anr.screenshot_id }}" class="link-button" onclick="scrollToScreenshot('{{ anr.screenshot_id }}')">
                                        <i class="bi bi-camera"></i> Screenshot {{ anr.screenshot_id }}
                                    </a>
                                    {% else %}
                                    <span class="text-muted">No screenshot</span>
                                    {% endif %}
                                </td>
                                {% endif %}
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" type="button"
                                            data-bs-toggle="collapse" data-bs-target="#anr-detail-{{ loop.index }}"
                                            aria-expanded="false" aria-controls="anr-detail-{{ loop.index }}">
                                        <i class="bi bi-eye"></i> Details
                                    </button>
                                    <button class="btn btn-sm btn-outline-secondary copy-stack-btn"
                                            data-stack-index="anr-{{ loop.index }}">
                                        <i class="bi bi-clipboard"></i> Copy
                                    </button>
                                </td>
                            </tr>
                            <tr class="collapse" id="anr-detail-{{ loop.index }}">
                                <td colspan="{% if take_screenshots %}6{% else %}5{% endif %}">
                                    <div class="bg-light p-3 rounded">
                                        <h6 class="text-dark">ANR Details:</h6>
                                        <pre class="text-dark mb-0 text-start" id="stack-trace-anr-{{ loop.index }}" style="font-size: 0.9em; white-space: pre-wrap; text-align: left;">{{ anr.trace }}</pre>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <!-- Pagination for Crash Events -->
                <div class="pagination-container d-flex justify-content-between align-items-center mt-3">
                    <div class="d-flex align-items-center">
                        <label for="events-page-size" class="form-label me-2 mb-0">Show:</label>
                        <select class="form-select form-select-sm" id="events-page-size" style="width: auto;">
                            <option value="5">5</option>
                            <option value="10" selected>10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                    <nav aria-label="Crash Events Pagination">
                        <ul class="pagination pagination-sm mb-0" id="events-pagination">
                            <!-- Pagination will be generated by JavaScript -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
        {% else %}
        <div class="section-block">
            <h2 class="section-title">
                <i class="bi bi-exclamation-triangle text-danger"></i> Crash and ANR Events
            </h2>
            <div class="alert alert-info text-center">
                <i class="bi bi-info-circle"></i> No crash or ANR events detected in this test session.
            </div>
        </div>
        {% endif %}

        <!-- Property Violations List -->
        {% if take_screenshots %}
        {% if property_violations %}
        <div class="section-block">
            <h2 class="section-title">Property Violations</h2>
            <div class="table-responsive">
                <table class="table table-custom table-violations">
                    <thead>
                        <tr>
                            <th>Index</th>
                            <th>Property Name</th>
                            <th>Interaction Scenario Pages</th>
                        </tr>
                    </thead>
                    <tbody id="property-violations-container">
                        {% for violation in property_violations %}
                        <tr class="property-violation-row" data-page="1">
                            <td>{{ violation.index }}</td>
                            <td><span class="badge bg-light text-dark badge-custom">{{ violation.property_name }}</span></td>
                            <td>
                                <a href="#{{ violation.interaction_pages|last }}" class="link-button"
                                   onclick="scrollToScreenshot('{{ violation.interaction_pages|last }}')">
                                    {{ violation.interaction_pages[0] }} ~ {{ violation.interaction_pages[1] }}
                                </a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>

                <!-- Pagination for Property Violations -->
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <div class="d-flex align-items-center">
                        <label for="violations-page-size" class="form-label me-2 mb-0">Show:</label>
                        <select class="form-select form-select-sm" id="violations-page-size" style="width: auto;">
                            <option value="5">5</option>
                            <option value="10" selected>10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                    <nav aria-label="Property Violations Pagination">
                        <ul class="pagination pagination-sm mb-0" id="violations-pagination">
                            <!-- Pagination will be generated by JavaScript -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
        {% else %}
        <div class="section-block">
            <h2 class="section-title">Property Violations</h2>
            <div class="alert alert-info text-center">
                <i class="bi bi-info-circle"></i> No property violations detected in this test session.
            </div>
        </div>
        {% endif %}
        {% endif %}

        <!-- Property Checking Statistics -->
        <div class="section-block">
            <h2 class="section-title">Property Checking Statistics</h2>
            
            <!-- Search Controls for Property Statistics -->
            <div class="mb-4">
                <div class="d-flex align-items-center">
                    <div style="width: 33%;">
                        <div class="property-search-container">
                            <input type="text" class="form-control property-search-input property-stats-search-simple"
                                   id="property-stats-search"
                                   placeholder="Search properties by name..."
                                   data-target="property-stats-container"
                                   data-item-class="property-stat-row"
                                   data-pagination="stats-pagination"
                                   data-page-size="stats-page-size">
                            <button class="property-search-icon-btn" type="button" id="property-search-btn">
                                <i class="bi bi-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="ms-3">
                        <small class="text-muted search-results-count" id="property-search-results"></small>
                    </div>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-custom table-property-stats">
                    <thead>
                        <tr>
                            <th>Index</th>
                            <th>Property Name <span class="badge bg-primary ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ property_stats_summary.total_properties }}</span></th>
                            <th>Precondition Satisfied <span class="badge bg-success ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ property_stats_summary.total_precond_satisfied }}</span></th>
                            <th>Executed <span class="badge bg-info ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ property_stats_summary.total_executed }}</span></th>
                            <th>Passes <span class="badge bg-secondary ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ property_stats_summary.total_passes }}</span></th>
                            <th>Fails <span class="badge bg-danger ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ property_stats_summary.total_fails }}</span> <i class="bi bi-arrow-down-up text-muted sort-icon" id="fails-sort" data-column="fails" data-order="none" style="cursor: pointer;"></i></th>
                            <th>Errors <span class="badge bg-warning ms-2" style="font-size: 0.9rem; font-weight: 600;">{{ property_stats_summary.total_errors }}</span> <i class="bi bi-arrow-down-up text-muted sort-icon" id="errors-sort" data-column="errors" data-order="none" style="cursor: pointer;"></i></th>
                            <th>Error Details</th>
                        </tr>
                    </thead>
                    <tbody id="property-stats-container">
                        {% for property_name, test_result in property_stats.items() %}
                        <tr class="property-stat-row" data-page="1" 
                            data-index="{{ loop.index }}"
                            data-property-name="{{ property_name }}"
                            data-precond-satisfied="{{ test_result.precond_satisfied|default(0) }}"
                            data-executed="{{ test_result.executed|default(0) }}"
                            data-pass="{{ test_result.pass_count|default(0) }}"
                            data-fails="{{ test_result.fail|default(0) }}"
                            data-errors="{{ test_result.error|default(0) }}">
                            <td>{{ loop.index }}</td>
                            <td><span class="badge bg-light text-dark badge-custom">{{ property_name }}</span></td>
                            <td>{{ test_result.precond_satisfied|default(0) }}</td>
                            <td>{{ test_result.executed|default(0) }}</td>
                            <td>{{ test_result.pass_count|default(0) }}</td>
                            <td><span class="badge bg-danger text-white">{{ test_result.fail|default(0) }}</span></td>
                            <td><span class="badge bg-warning text-dark">{{ test_result.error|default(0) }}</span></td>
                            <td>
                                {% if (test_result.fail|default(0) > 0 or test_result.error|default(0) > 0) and property_name in property_error_details %}
                                    {% set error_list = property_error_details[property_name] %}
                                    {% set property_index = loop.index %}
                                    {% if error_list|length == 1 %}
                                        <!-- Single error - simple display -->
                                        <button class="btn btn-sm btn-outline-danger" type="button" data-bs-toggle="collapse"
                                                data-bs-target="#single-error-detail-{{ property_index }}" aria-expanded="false"
                                                aria-controls="single-error-detail-{{ property_index }}">
                                            <i class="bi bi-exclamation-triangle"></i> View Error
                                        </button>
                                    {% else %}
                                        <!-- Multiple errors - tabbed display -->
                                        <button class="btn btn-sm btn-outline-danger" type="button" data-bs-toggle="collapse"
                                                data-bs-target="#multi-error-detail-{{ property_index }}" aria-expanded="false"
                                                aria-controls="multi-error-detail-{{ property_index }}">
                                            <i class="bi bi-exclamation-triangle"></i> View {{ error_list|length }} Errors
                                        </button>
                                    {% endif %}
                                {% else %}
                                    <span class="text-muted">-</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% if (test_result.fail|default(0) > 0 or test_result.error|default(0) > 0) and property_name in property_error_details %}
                            {% set error_list = property_error_details[property_name] %}
                            {% set property_index = loop.index %}
                            {% if error_list|length == 1 %}
                                <!-- Single error detail row -->
                                <tr class="collapse property-detail-row" data-detail-for="{{ property_name }}" id="single-error-detail-{{ property_index }}">
                                    <td colspan="8">
                                        <div class="bg-light p-3 rounded">
                                            <div class="mb-2">
                                                <span class="badge bg-{{ 'danger' if error_list[0].state == 'fail' else 'warning' }}">
                                                    {{ error_list[0].state|upper }}
                                                </span>
                                                {% if error_list[0].occurrence_count > 1 %}
                                                    <span class="badge bg-info ms-2">
                                                        Occurred {{ error_list[0].occurrence_count }} times
                                                    </span>
                                                {% endif %}
                                                {% if error_list[0].startStepsCountList is defined and error_list[0].startStepsCountList|length > 0 %}
                                                    <span class="badge bg-secondary ms-2">
                                                        <i class="bi bi-step-forward"></i> Monkey Steps: {{ error_list[0].startStepsCountList|join(', ') }}
                                                    </span>
                                                {% endif %}
                                            </div>
                                            {% if error_list[0].short_description %}
                                                <div class="mb-2">
                                                    <strong>Error:</strong> <code>{{ error_list[0].short_description }}</code>
                                                </div>
                                            {% endif %}
                                            <details>
                                                <summary class="btn btn-sm btn-outline-secondary mb-2">Show Full Traceback</summary>
                                                <pre class="text-danger mb-0 text-start" style="font-size: 0.85rem; white-space: pre-wrap; text-align: left;">{{ error_list[0].traceback }}</pre>
                                            </details>
                                        </div>
                                    </td>
                                </tr>
                            {% else %}
                                <!-- Multiple errors detail row -->
                                <tr class="collapse property-detail-row" data-detail-for="{{ property_name }}" id="multi-error-detail-{{ property_index }}">
                                    <td colspan="8">
                                        <div class="bg-light p-3 rounded">
                                            <!-- Error summary -->
                                            <div class="mb-3">
                                                <h6 class="text-danger">Multiple Errors Detected</h6>
                                                <div class="d-flex flex-wrap gap-1">
                                                    {% for error in error_list %}
                                                        <span class="badge bg-{{ 'danger' if error.state == 'fail' else 'warning' }}">
                                                            {{ error.state|upper }} #{{ loop.index }}
                                                            {% if error.occurrence_count > 1 %} ({{ error.occurrence_count }}x){% endif %}
                                                            {% if error.startStepsCountList is defined and error.startStepsCountList|length > 0 %}
                                                                @{% if error.startStepsCountList|length == 1 %}{{ error.startStepsCountList[0] }}{% else %}{{ error.startStepsCountList[0] }}-{{ error.startStepsCountList[-1] }}{% endif %}
                                                            {% endif %}
                                                        </span>
                                                    {% endfor %}
                                                </div>
                                            </div>

                                            <!-- Error tabs -->
                                            <ul class="nav nav-pills nav-fill mb-3" id="multi-error-tabs-{{ property_index }}" role="tablist">
                                                {% for error in error_list %}
                                                <li class="nav-item" role="presentation">
                                                    <button class="nav-link {{ 'active' if loop.first else '' }} btn-sm"
                                                            id="multi-error-tab-{{ property_index }}-{{ loop.index }}"
                                                            data-bs-toggle="pill"
                                                            data-bs-target="#multi-error-content-{{ property_index }}-{{ loop.index }}"
                                                            type="button" role="tab"
                                                            aria-controls="multi-error-content-{{ property_index }}-{{ loop.index }}"
                                                            aria-selected="{{ 'true' if loop.first else 'false' }}">
                                                        <span class="badge bg-{{ 'danger' if error.state == 'fail' else 'warning' }} me-1">
                                                            {{ error.state|upper }}
                                                        </span>
                                                        #{{ loop.index }}
                                                    </button>
                                                </li>
                                                {% endfor %}
                                            </ul>

                                            <!-- Error content -->
                                            <div class="tab-content" id="multi-error-content-{{ property_index }}">
                                                {% for error in error_list %}
                                                <div class="tab-pane fade {{ 'show active' if loop.first else '' }}"
                                                     id="multi-error-content-{{ property_index }}-{{ loop.index }}"
                                                     role="tabpanel"
                                                     aria-labelledby="multi-error-tab-{{ property_index }}-{{ loop.index }}">
                                                    <div class="mb-2">
                                                        <span class="badge bg-{{ 'danger' if error.state == 'fail' else 'warning' }}">
                                                            {{ error.state|upper }} #{{ loop.index }}
                                                        </span>
                                                        <small class="text-muted ms-2">Error {{ loop.index }} of {{ loop.length }}</small>
                                                        {% if error.occurrence_count > 1 %}
                                                            <span class="badge bg-info ms-2">
                                                                {{ error.occurrence_count }} occurrences
                                                            </span>
                                                        {% endif %}
                                                        {% if error.startStepsCountList is defined and error.startStepsCountList|length > 0 %}
                                                            <span class="badge bg-secondary ms-2">
                                                                <i class="bi bi-step-forward"></i> Monkey Steps: {{ error.startStepsCountList|join(', ') }}
                                                            </span>
                                                        {% endif %}
                                                    </div>
                                                    {% if error.short_description %}
                                                        <div class="mb-2">
                                                            <strong>Error:</strong> <code>{{ error.short_description }}</code>
                                                        </div>
                                                    {% endif %}
                                                    <details>
                                                        <summary class="btn btn-sm btn-outline-secondary mb-2">Show Full Traceback</summary>
                                                        <pre class="text-danger mb-0 text-start" style="font-size: 0.85rem; white-space: pre-wrap; text-align: left;">{{ error.traceback }}</pre>
                                                    </details>
                                                </div>
                                                {% endfor %}
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            {% endif %}
                        {% endif %}
                        {% endfor %}
                    </tbody>
                </table>
                
                <!-- Pagination for Property Checking Statistics -->
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <div class="d-flex align-items-center">
                        <label for="stats-page-size" class="form-label me-2 mb-0">Show:</label>
                        <select class="form-select form-select-sm" id="stats-page-size" style="width: auto;">
                            <option value="5">5</option>
                            <option value="10" selected>10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                    <nav aria-label="Property Stats Pagination">
                        <ul class="pagination pagination-sm mb-0" id="stats-pagination">
                            <!-- Pagination will be generated by JavaScript -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white text-center py-4">
        <div class="container">
            <p class="mb-0">Kea2 Test Report | Generated at: {{ timestamp }}</p>
        </div>
    </footer>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Draw coverage trend chart
        document.addEventListener('DOMContentLoaded', function() {
            var coverageData = {{ coverage_data|safe }};
            console.log("Coverage data points:", coverageData.length);

            coverageData.sort(function(a, b) {
                return a.stepsCount - b.stepsCount;
            });
            
            var steps = coverageData.map(function(item) { return item.stepsCount; });
            var coverages = coverageData.map(function(item) { return item.coverage; });
            var testedActivities = coverageData.map(function(item) { return item.testedActivitiesCount; });

            if (steps.length > 0 && steps[0] > 0) {
                steps.unshift(0);
                coverages.unshift(0);
                testedActivities.unshift(0);
            }

            console.log("Steps with zero point:", steps);
            console.log("Coverage values with zero point:", coverages);

            var ctx = document.getElementById('coverageChart').getContext('2d');
            var chart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: steps,
                    datasets: [
                        {
                            label: 'Activity Coverage (%)',
                            data: coverages.map((value, index) => ({x: steps[index], y: value})),
                            borderColor: '#3498db',
                            backgroundColor: 'rgba(52, 152, 219, 0.1)',
                            borderWidth: 3,
                            fill: true,
                            tension: 0.4,
                            yAxisID: 'y',
                            pointRadius: 4,
                            pointHoverRadius: 6
                        },
                        {
                            label: 'Tested Activities',
                            data: testedActivities.map((value, index) => ({x: steps[index], y: value})),
                            borderColor: '#2ecc71',
                            backgroundColor: 'rgba(46, 204, 113, 0.1)',
                            borderWidth: 3,
                            fill: true,
                            tension: 0.4,
                            yAxisID: 'y1',
                            pointRadius: 4,
                            pointHoverRadius: 6
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    aspectRatio: 2,
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 15,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            borderColor: 'rgba(255, 255, 255, 0.2)',
                            borderWidth: 1,
                            padding: 10,
                            displayColors: true,
                            callbacks: {
                                label: function(context) {
                                    var label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.datasetIndex === 0) {
                                        label += context.parsed.y.toFixed(2) + '%';
                                    } else {
                                        label += context.parsed.y;
                                    }
                                    return label;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            type: 'linear',
                            beginAtZero: true,
                            max: steps.length > 0 ? Math.max(...steps) : 10,
                            grid: {
                                display: false
                            },
                            title: {
                                display: true,
                                text: 'Steps Count',
                                font: {
                                    size: 14
                                }
                            },
                            ticks: {
                                stepSize: steps.length > 0 ? Math.max(1, Math.ceil(Math.max(...steps) / 10)) : 1,
                                callback: function(value) {
                                    if (Number.isInteger(value) && value <= (steps.length > 0 ? Math.max(...steps) : 10)) {
                                    return value;
                                    }
                                    return null;
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Activity Coverage (%)',
                                font: {
                                    size: 14
                                }
                            },
                            grid: {
                                borderDash: [5, 5]
                            }
                        },
                        y1: {
                            position: 'right',
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Tested Activities',
                                font: {
                                    size: 14
                                }
                            },
                            grid: {
                                display: false
                            }
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    hover: {
                        mode: 'index',
                        intersect: false
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });
            
            // Draw property execution trend chart
            var propertyExecutionData = {{ property_execution_data|safe }};
            console.log("Property execution data points:", propertyExecutionData.length);

            // Ensure we have valid data
            if (propertyExecutionData.length === 0) {
                propertyExecutionData = [{"stepsCount": 0, "executedPropertiesCount": 0}];
            }

            propertyExecutionData.sort(function(a, b) {
                return a.stepsCount - b.stepsCount;
            });
            
            var propSteps = propertyExecutionData.map(function(item) { return item.stepsCount; });
            var executedProps = propertyExecutionData.map(function(item) { return item.executedPropertiesCount; });

            // Add zero starting point if needed
            if (propSteps.length > 0 && propSteps[0] > 0) {
                propSteps.unshift(0);
                executedProps.unshift(0);
            }

            console.log("Property execution steps:", propSteps);
            console.log("Executed properties values:", executedProps);

            var propCtx = document.getElementById('propertyExecutionChart').getContext('2d');
            var propChart = new Chart(propCtx, {
                type: 'line',
                data: {
                    labels: propSteps,
                    datasets: [
                        {
                            label: 'Executed Properties',
                            data: executedProps.map((value, index) => ({x: propSteps[index], y: value})),
                            borderColor: '#e74c3c',
                            backgroundColor: 'rgba(231, 76, 60, 0.1)',
                            borderWidth: 3,
                            fill: true,
                            tension: 0.4,
                            pointRadius: 4,
                            pointHoverRadius: 6
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    aspectRatio: 2,
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 15,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            borderColor: 'rgba(255, 255, 255, 0.2)',
                            borderWidth: 1,
                            padding: 10,
                            displayColors: true,
                            callbacks: {
                                label: function(context) {
                                    return 'Executed Properties: ' + context.parsed.y;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            type: 'linear',
                            beginAtZero: true,
                            max: propSteps.length > 0 ? Math.max(...propSteps) : 10,
                            grid: {
                                display: false
                            },
                            title: {
                                display: true,
                                text: 'Steps Count',
                                font: {
                                    size: 14
                                }
                            },
                            ticks: {
                                stepSize: propSteps.length > 0 ? Math.max(1, Math.ceil(Math.max(...propSteps) / 10)) : 1,
                                callback: function(value) {
                                    if (Number.isInteger(value) && value <= (propSteps.length > 0 ? Math.max(...propSteps) : 10)) {
                                        return value;
                                    }
                                    return null;
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Executed Properties',
                                font: {
                                    size: 14
                                }
                            },
                            grid: {
                                borderDash: [5, 5]
                            },
                            ticks: {
                                stepSize: 1,
                                callback: function(value) {
                                    if (Number.isInteger(value)) {
                                        return value;
                                    }
                                    return null;
                                }
                            }
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    hover: {
                        mode: 'index',
                        intersect: false
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });
            
            // Draw crash timeline chart
            var crashTimelineData = {{ crash_timeline_data|default('{}')|safe }};
            if (crashTimelineData && Object.keys(crashTimelineData).length > 0) {
                drawCrashTimelineChart(crashTimelineData);
            }
            
            // Initialize crash events functionality
            initCrashAnalysis();
            
            // Initialize pagination for Activities table
            initPagination('activities-container', 'activity-row', 'activities-pagination', 'activities-page-size');

            // Initialize activity sorting
            initActivitiesSorting();

            // Initialize activity searching
            initActivitiesSearching();

            // Initialize activities page size selector
            initActivitiesPageSize();

            // Initialize property statistics searching
            initPropertySearching();
            
            // Initialize pagination for Property tables
            initPagination('property-violations-container', 'property-violation-row', 'violations-pagination', 'violations-page-size');
            initPagination('property-stats-container', 'property-stat-row', 'stats-pagination', 'stats-page-size');
            
            // Initialize sorting for Property Checking Statistics
            initSorting();
            
            // Activity sorting function
            function initActivitySorting() {
                const sortButtons = document.querySelectorAll('.activity-sort-btn');
                
                sortButtons.forEach(function(button) {
                    button.addEventListener('click', function() {
                        const sortType = this.dataset.sort;
                        const currentOrder = this.dataset.order;
                        const parentTab = this.closest('.tab-pane');
                        const isTestedTab = parentTab.id === 'tested-activities';
                        
                        // Toggle sort order
                        const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
                        
                        this.dataset.order = newOrder;
                        const icon = this.querySelector('.sort-icon');
                        
                        if (newOrder === 'asc') {
                            icon.className = 'bi bi-arrow-up sort-icon btn-arrow';
                        } else {
                            icon.className = 'bi bi-arrow-down sort-icon btn-arrow';
                        }
                        
                        // Sort activities
                        sortActivities(sortType, newOrder, isTestedTab);
                    });
                });
                
                function sortActivities(sortType, order, isTestedTab) {
                    const containerId = isTestedTab ? 'tested-activities-container' : 'all-activities-container';
                    const itemClass = isTestedTab ? 'tested-activity' : 'all-activity';
                    const paginationId = isTestedTab ? 'tested-pagination' : 'all-pagination';
                    const pageSizeSelectId = isTestedTab ? 'tested-page-size' : 'all-page-size';
                    
                    const container = document.getElementById(containerId);
                    const items = Array.from(container.getElementsByClassName(itemClass));
                    
                    items.sort(function(a, b) {
                        const badgeA = a.querySelector('.traversal-badge');
                        const badgeB = b.querySelector('.traversal-badge');
                        
                        // Extract traversal count from badge text like "👁 5 times"
                        const valueA = badgeA ? parseInt(badgeA.textContent.match(/\d+/)[0]) || 0 : 0;
                        const valueB = badgeB ? parseInt(badgeB.textContent.match(/\d+/)[0]) || 0 : 0;
                        
                        if (order === 'asc') {
                            return valueA - valueB;
                        } else {
                            return valueB - valueA;
                        }
                    });
                    
                    // Clear container and append sorted items
                    container.innerHTML = '';
                    items.forEach(function(item) {
                        container.appendChild(item);
                    });
                    
                    // Check if there's an active search and reapply it
                    const searchInputId = isTestedTab ? 'tested-activity-search' : 'all-activity-search';
                    const searchInput = document.getElementById(searchInputId);
                    if (searchInput && searchInput.value.trim() !== '') {
                        // Reapply search filter after sorting
                        performActivitySearch(searchInput);
                    } else {
                        // No active search, just re-initialize pagination
                    initPagination(containerId, itemClass, paginationId, pageSizeSelectId);
                    }
                }
            }
            
            // Simplified sorting function for Fails and Errors columns (Property Checking Statistics only)
            function initSorting() {
                // Only select sort icons that are NOT activities sort icons
                const sortIcons = document.querySelectorAll('.sort-icon:not(.activities-sort-icon)');

                sortIcons.forEach(function(icon) {
                    icon.addEventListener('click', function() {
                        const column = this.dataset.column;
                        const currentOrder = this.dataset.order;

                        // Reset all other property sort icons (not activities)
                        sortIcons.forEach(function(otherIcon) {
                            if (otherIcon !== icon) {
                                otherIcon.dataset.order = 'none';
                                otherIcon.className = 'bi bi-arrow-down-up sort-icon';
                                otherIcon.style.color = '#6c757d';
                            }
                        });

                        // Toggle current sort order
                        let newOrder;
                        if (currentOrder === 'none' || currentOrder === 'desc') {
                            newOrder = 'asc';
                            this.className = 'bi bi-arrow-up sort-icon active asc';
                            this.style.color = '#28a745';
                        } else {
                            newOrder = 'desc';
                            this.className = 'bi bi-arrow-down sort-icon active desc';
                            this.style.color = '#dc3545';
                        }

                        this.dataset.order = newOrder;
                        sortTable(column, newOrder);
                    });
                });
                
                function sortTable(column, order) {
                    const container = document.getElementById('property-stats-container');
                    const rows = Array.from(container.getElementsByClassName('property-stat-row'));
                    const detailRowMap = new Map();

                    // Capture current detail rows so they can move with their parent property row
                    const detailRows = Array.from(container.querySelectorAll('.property-detail-row'));
                    detailRows.forEach(function(detailRow) {
                        const key = detailRow.dataset.detailFor;
                        if (!key) return;
                        if (!detailRowMap.has(key)) {
                            detailRowMap.set(key, []);
                        }
                        detailRowMap.get(key).push(detailRow);
                    });
                    
                    rows.sort(function(a, b) {
                        let valueA, valueB;
                        
                        if (column === 'fails') {
                            valueA = parseInt(a.dataset.fails);
                            valueB = parseInt(b.dataset.fails);
                        } else if (column === 'errors') {
                            valueA = parseInt(a.dataset.errors);
                            valueB = parseInt(b.dataset.errors);
                        }
                        
                        if (order === 'asc') {
                            return valueA - valueB;
                        } else {
                            return valueB - valueA;
                        }
                    });
                    
                    const fragment = document.createDocumentFragment();
                    rows.forEach(function(row) {
                        fragment.appendChild(row);
                        const detailKey = row.dataset.propertyName;
                        const relatedDetailRows = detailRowMap.get(detailKey) || [];
                        relatedDetailRows.forEach(function(detailRow) {
                            fragment.appendChild(detailRow);
                        });
                    });

                    container.innerHTML = '';
                    container.appendChild(fragment);
                    
                    // Re-initialize pagination after sorting
                    initPagination('property-stats-container', 'property-stat-row', 'stats-pagination', 'stats-page-size');
                }
            }
            
            // Function to handle page navigation
            function goToPage(pageNumber, containerId, itemClass, itemsPerPage, paginationId) {
                const container = document.getElementById(containerId);
                const allItems = Array.from(container.getElementsByClassName(itemClass));
                const paginationElement = document.getElementById(paginationId);
                
                console.log('goToPage called with:', {pageNumber, containerId, itemClass, itemsPerPage, paginationId});
                console.log('Total items found:', allItems.length);
                
                // Get items that should be visible based on search filter
                const filteredItems = allItems.filter(item => {
                    const searchVisible = item.getAttribute('data-search-visible');
                    const shouldShow = searchVisible === null || searchVisible === 'true';
                    return shouldShow;
                });
                
                console.log('Filtered items count:', filteredItems.length);
                console.log('Items with search-visible=true:', allItems.filter(item => item.getAttribute('data-search-visible') === 'true').length);
                console.log('Items with search-visible=false:', allItems.filter(item => item.getAttribute('data-search-visible') === 'false').length);
                console.log('Items with search-visible=null:', allItems.filter(item => item.getAttribute('data-search-visible') === null).length);
                
                // Update pagination active state
                if (paginationElement) {
                    const pageItems = paginationElement.getElementsByClassName('page-item');
                    for (let i = 0; i < pageItems.length; i++) {
                        if (pageItems[i].textContent.trim() === pageNumber.toString()) {
                            pageItems[i].className = 'page-item active';
                        } else if (pageItems[i].textContent.trim() !== '«' && pageItems[i].textContent.trim() !== '»') {
                            pageItems[i].className = 'page-item';
                        }
                    }
                }
                
                // Hide all items first
                console.log('Hiding all items...');
                allItems.forEach((item, index) => {
                    item.style.display = 'none';
                });
                
                // Show items for current page (only from filtered items)
                const startIndex = (pageNumber - 1) * itemsPerPage;
                const endIndex = Math.min(startIndex + itemsPerPage, filteredItems.length);
                
                console.log('Showing items from index', startIndex, 'to', endIndex - 1);
                
                for (let i = startIndex; i < endIndex; i++) {
                    if (filteredItems[i]) {
                        filteredItems[i].style.display = '';
                        console.log('Showing item', i, ':', filteredItems[i].querySelector('.activity-name')?.textContent);
                    }
                }
                
                console.log('goToPage completed');
            }
            
            // Pagination function
            function initPagination(containerId, itemClass, paginationId, pageSizeSelectId) {
                const container = document.getElementById(containerId);
                const pageSizeSelect = document.getElementById(pageSizeSelectId);
                if (!container) return;
                
                // Remove existing event listener to prevent duplicate bindings
                if (pageSizeSelect && !pageSizeSelect.hasAttribute('data-listener-bound')) {
                    pageSizeSelect.addEventListener('change', function() {
                        const newItemsPerPage = parseInt(this.value);
                        renderPagination();
                        goToPage(1, containerId, itemClass, newItemsPerPage, paginationId);
                    });
                    // Mark as having listener bound
                    pageSizeSelect.setAttribute('data-listener-bound', 'true');
                }
                
                function renderPagination() {
                    const allItems = Array.from(container.getElementsByClassName(itemClass));
                    
                    // Always get current page size from select element
                    const currentPageSizeSelect = document.getElementById(pageSizeSelectId);
                    const currentItemsPerPage = currentPageSizeSelect ? parseInt(currentPageSizeSelect.value) : 10;
                    
                    // Use same filtering logic as goToPage function
                    const filteredItems = allItems.filter(item => {
                        const searchVisible = item.getAttribute('data-search-visible');
                        // If no search filter is applied, show all items
                        return searchVisible === null || searchVisible === 'true';
                    });
                    
                    const totalItems = filteredItems.length;
                    const totalPages = Math.max(1, Math.ceil(totalItems / currentItemsPerPage));
                    
                    // Create pagination
                    const paginationElement = document.getElementById(paginationId);
                    if (!paginationElement) return;
                    
                    // Clear pagination
                    paginationElement.innerHTML = '';
                    
                    // Don't show pagination if there's only one page or no items
                    if (totalPages <= 1) {
                        // Hide the entire pagination container when not needed
                        const paginationContainer = paginationElement.closest('.pagination-container');
                        if (paginationContainer) {
                            paginationContainer.style.display = 'none';
                        }
                        return;
                    }
                    
                    // Show the pagination container when needed
                    const paginationContainer = paginationElement.closest('.pagination-container');
                    if (paginationContainer) {
                        paginationContainer.style.display = '';
                    }
                    
                    // Previous button
                    const prevLi = document.createElement('li');
                    prevLi.className = 'page-item disabled';
                    prevLi.innerHTML = '<a class="page-link" href="#" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a>';
                    paginationElement.appendChild(prevLi);
                    
                    // Add page numbers
                    for (let i = 1; i <= totalPages; i++) {
                        const pageLi = document.createElement('li');
                        pageLi.className = i === 1 ? 'page-item active' : 'page-item';
                        pageLi.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                        pageLi.addEventListener('click', function(e) {
                            e.preventDefault();
                            goToPage(i, containerId, itemClass, currentItemsPerPage, paginationId);
                        });
                        paginationElement.appendChild(pageLi);
                    }
                    
                    // Next button
                    const nextLi = document.createElement('li');
                    nextLi.className = totalPages <= 1 ? 'page-item disabled' : 'page-item';
                    nextLi.innerHTML = '<a class="page-link" href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a>';
                    paginationElement.appendChild(nextLi);
                    
                    // Add event listeners to prev/next buttons
                    if (paginationElement.firstChild) {
                        paginationElement.firstChild.addEventListener('click', function(e) {
                            e.preventDefault();
                            const activePage = paginationElement.querySelector('.active');
                            if (activePage && activePage.previousElementSibling && activePage.previousElementSibling.previousElementSibling) {
                                const pageNum = parseInt(activePage.textContent) - 1;
                                if (pageNum >= 1) {
                                    goToPage(pageNum, containerId, itemClass, currentItemsPerPage, paginationId);
                                }
                            }
                        });
                    }
                    
                    if (paginationElement.lastChild) {
                        paginationElement.lastChild.addEventListener('click', function(e) {
                            e.preventDefault();
                            const activePage = paginationElement.querySelector('.active');
                            if (activePage && activePage.nextElementSibling && activePage.nextElementSibling.nextElementSibling) {
                                const pageNum = parseInt(activePage.textContent) + 1;
                                if (pageNum <= totalPages) {
                                    goToPage(pageNum, containerId, itemClass, currentItemsPerPage, paginationId);
                                }
                            }
                        });
                    }
                }
                
                // Initial render
                renderPagination();
                // Always call goToPage to ensure items are displayed correctly, even if no pagination is shown
                const currentItemsPerPage = pageSizeSelect ? parseInt(pageSizeSelect.value) : 10;
                goToPage(1, containerId, itemClass, currentItemsPerPage, paginationId);
            }
            
            // Scroll functionality
            const screenshots = document.getElementById('screenshots');
            if (screenshots) {
                screenshots.addEventListener('wheel', function(e) {
                    if (e.deltaY !== 0) {
                        e.preventDefault();
                        screenshots.scrollLeft += e.deltaY;
                    }
                });
            }
            
            // Beautify screenshot captions
            function beautifyScreenshotCaptions() {
                const captions = document.querySelectorAll('.screenshot-caption');
                captions.forEach(function(caption) {
                    const originalText = caption.textContent.trim();
                    
                    // Handle Monkey Step format: "1. Monkey Step 6: SCROLL_TOP_DOWN"
                    const monkeyStepMatch = originalText.match(/^(\d+)\.\s*Monkey Step (\d+):\s*(.+)$/);
                    if (monkeyStepMatch) {
                        const stepIndex = monkeyStepMatch[1];
                        const monkeyStep = monkeyStepMatch[2];
                        const action = monkeyStepMatch[3];
                        
                        caption.innerHTML = `
                            <div class="step-number">${stepIndex}. Monkey Step ${monkeyStep}</div>
                            <div class="step-action">${action}</div>
                        `;
                        return;
                    }
                    
                    // Handle Script format: "1. click" or similar
                    const scriptMatch = originalText.match(/^(\d+)\.\s*(.+)$/);
                    if (scriptMatch) {
                        const stepIndex = scriptMatch[1];
                        const action = scriptMatch[2];
                        
                        // Check if it's a property info
                        if (action.includes(':')) {
                            const parts = action.split(':');
                            if (parts.length === 2) {
                                caption.innerHTML = `
                                    <div class="step-number">${stepIndex}. ${parts[0].trim()}</div>
                                    <div class="step-action">${parts[1].trim()}</div>
                                `;
                                return;
                            }
                        }
                        
                        // Simple action
                        caption.innerHTML = `
                            <div class="step-number">${stepIndex}. Script Step</div>
                            <div class="step-action">${action}</div>
                        `;
                    }
                });
            }
            
            // Call beautify function after DOM is ready
            beautifyScreenshotCaptions();
            
            // Crash analysis functions
            function initCrashAnalysis() {
                // Initialize event filtering
                var filterButtons = document.querySelectorAll('input[name="event-filter"]');
                filterButtons.forEach(function(button) {
                    button.addEventListener('change', function() {
                        filterCrashEvents(this.id);
                    });
                });

                // Initialize copy buttons for stack traces
                var copyButtons = document.querySelectorAll('.copy-stack-btn');
                copyButtons.forEach(function(button) {
                    button.addEventListener('click', function() {
                        var stackIndex = this.dataset.stackIndex;
                        copyStackTrace(stackIndex);
                    });
                });

                // Initialize page size selector for crash events
                var pageSizeSelect = document.getElementById('events-page-size');
                if (pageSizeSelect) {
                    pageSizeSelect.addEventListener('change', function() {
                        updateCrashEventsPagination();
                    });
                }

                // Initialize pagination for crash events
                updateCrashEventsPagination();
            }
            
            function filterCrashEvents(filterType) {
                // Simply update pagination, which will handle filtering and display
                updateCrashEventsPagination();
            }

            function updateCrashEventsPagination() {
                var container = document.getElementById('crash-events-container');
                var pagination = document.getElementById('events-pagination');
                var pageSizeSelect = document.getElementById('events-page-size');

                if (!container || !pagination || !pageSizeSelect) return;

                // Get all rows and determine which should be visible based on current filter
                var allRows = Array.from(container.querySelectorAll('.event-row'));
                var currentFilter = getCurrentEventFilter();

                var visibleRows = allRows.filter(function(row) {
                    var rowType = row.dataset.type;
                    switch(currentFilter) {
                        case 'all-events':
                            return true;
                        case 'crashes-only':
                            return rowType === 'crash';
                        case 'anr-only':
                            return rowType === 'anr';
                        default:
                            return true;
                    }
                });

                var pageSize = parseInt(pageSizeSelect.value) || 10;
                var totalPages = Math.ceil(visibleRows.length / pageSize);
                var currentPage = 1;

                // Hide all rows first
                allRows.forEach(function(row) {
                    row.style.display = 'none';
                    var detailRow = row.nextElementSibling;
                    if (detailRow && detailRow.classList.contains('collapse')) {
                        detailRow.style.display = 'none';
                    }
                });

                // Show rows for current page
                var startIndex = (currentPage - 1) * pageSize;
                var endIndex = Math.min(startIndex + pageSize, visibleRows.length);

                for (var i = startIndex; i < endIndex; i++) {
                    visibleRows[i].style.display = '';
                    var detailRow = visibleRows[i].nextElementSibling;
                    if (detailRow && detailRow.classList.contains('collapse')) {
                        detailRow.style.display = '';
                    }
                }

                // Store current state for pagination callback
                window.crashEventsState = {
                    visibleRows: visibleRows,
                    pageSize: pageSize,
                    totalPages: totalPages
                };

                // Update pagination controls
                updatePaginationControls('events-pagination', currentPage, totalPages, function(page) {
                    showCrashEventsPage(page, window.crashEventsState.visibleRows, window.crashEventsState.pageSize);
                });
            }

            function showCrashEventsPage(page, visibleRows, pageSize) {
                // Hide all visible rows
                visibleRows.forEach(function(row) {
                    row.style.display = 'none';
                    var detailRow = row.nextElementSibling;
                    if (detailRow && detailRow.classList.contains('collapse')) {
                        detailRow.style.display = 'none';
                    }
                });

                // Show rows for the specified page
                var startIndex = (page - 1) * pageSize;
                var endIndex = Math.min(startIndex + pageSize, visibleRows.length);

                for (var i = startIndex; i < endIndex; i++) {
                    visibleRows[i].style.display = '';
                    var detailRow = visibleRows[i].nextElementSibling;
                    if (detailRow && detailRow.classList.contains('collapse')) {
                        detailRow.style.display = '';
                    }
                }

                // Update pagination controls to reflect current page
                var totalPages = Math.ceil(visibleRows.length / pageSize);
                var pagination = document.getElementById('events-pagination');
                if (pagination) {
                    // Update active page
                    var pageItems = pagination.querySelectorAll('.page-item');
                    pageItems.forEach(function(item, index) {
                        // Skip first (previous) and last (next) buttons
                        if (index > 0 && index < pageItems.length - 1) {
                            var pageNum = parseInt(item.textContent);
                            if (pageNum === page) {
                                item.classList.add('active');
                            } else {
                                item.classList.remove('active');
                            }
                        }
                    });

                    // Update previous button state
                    if (pageItems.length > 0) {
                        var prevButton = pageItems[0];
                        if (page === 1) {
                            prevButton.classList.add('disabled');
                        } else {
                            prevButton.classList.remove('disabled');
                        }
                    }

                    // Update next button state
                    if (pageItems.length > 1) {
                        var nextButton = pageItems[pageItems.length - 1];
                        if (page === totalPages) {
                            nextButton.classList.add('disabled');
                        } else {
                            nextButton.classList.remove('disabled');
                        }
                    }
                }
            }

            function getCurrentEventFilter() {
                var filterButtons = document.querySelectorAll('input[name="event-filter"]');
                for (var i = 0; i < filterButtons.length; i++) {
                    if (filterButtons[i].checked) {
                        return filterButtons[i].id;
                    }
                }
                return 'all-events'; // default
            }

            function updatePaginationControls(paginationId, currentPage, totalPages, onPageClick) {
                var pagination = document.getElementById(paginationId);
                if (!pagination) return;

                pagination.innerHTML = '';

                if (totalPages <= 1) {
                    // Hide the entire pagination container when not needed
                    var paginationContainer = pagination.closest('.pagination-container');
                    if (paginationContainer) {
                        paginationContainer.style.display = 'none';
                    }
                    return;
                }

                // Show the pagination container when needed
                var paginationContainer = pagination.closest('.pagination-container');
                if (paginationContainer) {
                    paginationContainer.style.display = '';
                }

                // Previous button
                var prevLi = document.createElement('li');
                prevLi.className = 'page-item' + (currentPage === 1 ? ' disabled' : '');
                var prevLink = document.createElement('a');
                prevLink.className = 'page-link';
                prevLink.href = '#';
                prevLink.setAttribute('aria-label', 'Previous');
                prevLink.innerHTML = '<span aria-hidden="true">&laquo;</span>';

                prevLink.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    // Get current page dynamically to avoid stale closure values
                    var currentActivePage = getCurrentPageNumber(paginationId);
                    if (currentActivePage > 1 && !prevLi.classList.contains('disabled')) {
                        onPageClick(currentActivePage - 1);
                    }
                });

                prevLi.appendChild(prevLink);
                pagination.appendChild(prevLi);

                // Page numbers
                for (var i = 1; i <= totalPages; i++) {
                    var li = document.createElement('li');
                    li.className = 'page-item' + (i === currentPage ? ' active' : '');
                    var link = document.createElement('a');
                    link.className = 'page-link';
                    link.href = '#';
                    link.textContent = i;
                    link.addEventListener('click', (function(page) {
                        return function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            onPageClick(page);
                        };
                    })(i));
                    li.appendChild(link);
                    pagination.appendChild(li);
                }

                // Next button
                var nextLi = document.createElement('li');
                nextLi.className = 'page-item' + (currentPage === totalPages ? ' disabled' : '');
                var nextLink = document.createElement('a');
                nextLink.className = 'page-link';
                nextLink.href = '#';
                nextLink.setAttribute('aria-label', 'Next');
                nextLink.innerHTML = '<span aria-hidden="true">&raquo;</span>';

                nextLink.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    // Get current page dynamically to avoid stale closure values
                    var currentActivePage = getCurrentPageNumber(paginationId);
                    if (currentActivePage < totalPages && !nextLi.classList.contains('disabled')) {
                        onPageClick(currentActivePage + 1);
                    }
                });

                nextLi.appendChild(nextLink);
                pagination.appendChild(nextLi);
            }

            function getCurrentPageNumber(paginationId) {
                var pagination = document.getElementById(paginationId);
                if (!pagination) return 1;

                var activeItem = pagination.querySelector('.page-item.active');
                if (activeItem) {
                    var pageText = activeItem.textContent.trim();
                    var pageNum = parseInt(pageText);
                    return isNaN(pageNum) ? 1 : pageNum;
                }
                return 1;
            }

            function copyStackTrace(index) {
                var stackTraceElement = document.getElementById('stack-trace-' + index);
                if (!stackTraceElement) return;
                
                var stackTrace = stackTraceElement.textContent;
                
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(stackTrace).then(function() {
                        showCopyNotification('Stack trace copied to clipboard!');
                    }).catch(function(err) {
                        console.error('Failed to copy stack trace: ', err);
                        showCopyNotification('Failed to copy stack trace', 'error');
                    });
                } else {
                    // Fallback for older browsers
                    var textArea = document.createElement('textarea');
                    textArea.value = stackTrace;
                    document.body.appendChild(textArea);
                    textArea.select();
                    try {
                        document.execCommand('copy');
                        showCopyNotification('Stack trace copied to clipboard!');
                    } catch (err) {
                        console.error('Fallback copy failed: ', err);
                        showCopyNotification('Failed to copy stack trace', 'error');
                    }
                    document.body.removeChild(textArea);
                }
            }
            
            function showCopyNotification(message, type) {
                type = type || 'success';
                
                // Create notification element
                var notification = document.createElement('div');
                notification.className = 'alert alert-' + (type === 'error' ? 'danger' : 'success') + ' position-fixed';
                notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
                notification.innerHTML = '<i class="bi bi-' + (type === 'error' ? 'exclamation-triangle' : 'check-circle') + '"></i> ' + message;
                
                document.body.appendChild(notification);
                
                // Auto remove after 3 seconds
                setTimeout(function() {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 3000);
            }
        });
        
        // Global activity search functions
        function performActivitySearch(searchInput) {
            const searchTerm = searchInput.value.toLowerCase().trim();
            const containerId = searchInput.dataset.target;
            const itemClass = searchInput.dataset.itemClass;
            const paginationId = searchInput.dataset.pagination;
            const pageSizeSelectId = searchInput.dataset.pageSize;
            
            const container = document.getElementById(containerId);
            const items = Array.from(container.getElementsByClassName(itemClass));
            
            // Filter and count matching items
            let visibleCount = 0;
            let totalCount = items.length;
            
            items.forEach(function(item, index) {
                const activityName = item.querySelector('.activity-name');
                if (activityName) {
                    const text = activityName.textContent.toLowerCase();
                    const matches = searchTerm === '' || text.includes(searchTerm);
                    
                    if (matches) {
                        item.setAttribute('data-search-visible', 'true');
                        visibleCount++;
                    } else {
                        item.setAttribute('data-search-visible', 'false');
                    }
                } else {
                    // If no activity name found, hide the item
                    item.setAttribute('data-search-visible', 'false');
                }
            });
            
            // Update search results count
            updateSearchResultsCount(searchInput, visibleCount, totalCount, searchTerm);
            
            // Re-initialize pagination and go to first page
            initPagination(containerId, itemClass, paginationId, pageSizeSelectId);
            
            // Always go to page 1 after search
            const currentPageSize = document.getElementById(pageSizeSelectId) ? 
                parseInt(document.getElementById(pageSizeSelectId).value) : 10;
            
            goToPage(1, containerId, itemClass, currentPageSize, paginationId);
        }
        
        function updateSearchResultsCount(searchInput, visibleCount, totalCount, searchTerm) {
            const isTestedTab = searchInput.id.includes('tested');
            const resultsElementId = isTestedTab ? 'tested-search-results' : 'all-search-results';
            const resultsElement = document.getElementById(resultsElementId);
            
            if (resultsElement) {
                if (searchTerm === '') {
                    resultsElement.innerHTML = `<span class="text-muted">Showing all ${totalCount} activities - Type and click <i class="bi bi-search"></i> or press Enter to search</span>`;
                } else if (visibleCount === 0) {
                    resultsElement.innerHTML = `<span class="text-danger">No activities found for "${searchTerm}"</span>`;
                } else if (visibleCount === totalCount) {
                    resultsElement.innerHTML = `<span class="text-success">All ${totalCount} activities match "${searchTerm}"</span>`;
                } else {
                    resultsElement.innerHTML = `<span class="text-info">Found ${visibleCount} of ${totalCount} activities for "${searchTerm}"</span>`;
                }
            }
        }
        
        // Activity searching function
        function initActivitySearching() {
            const searchInputs = document.querySelectorAll('.activity-search-input');
            const searchButtons = document.querySelectorAll('.search-btn');
            const clearButtons = document.querySelectorAll('.search-clear-btn');
            
            // Initialize search functionality for each input
            searchInputs.forEach(function(input) {
                // Search on Enter key
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        performActivitySearch(this);
                    } else if (e.key === 'Escape') {
                        clearActivitySearch(this);
                    }
                });
            });
            
            // Initialize search button functionality
            searchButtons.forEach(function(button) {
                button.addEventListener('click', function() {
                    const targetInputId = this.dataset.target;
                    const targetInput = document.getElementById(targetInputId);
                    if (targetInput) {
                        performActivitySearch(targetInput);
                    }
                });
            });
            
            // Initialize clear button functionality
            clearButtons.forEach(function(button) {
                button.addEventListener('click', function() {
                    const targetInputId = this.dataset.target;
                    const targetInput = document.getElementById(targetInputId);
                    if (targetInput) {
                        clearActivitySearch(targetInput);
                    }
                });
            });
            
            function clearActivitySearch(searchInput) {
                searchInput.value = '';
                performActivitySearch(searchInput);
                searchInput.focus();
            }
        }
        
        // Property statistics searching function
        function initPropertySearching() {
            const searchInput = document.getElementById('property-stats-search');
            const searchButton = document.getElementById('property-search-btn');

            if (!searchInput) return;

            // Search on Enter key and clear on Escape
            searchInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    performPropertySearch(this);
                } else if (e.key === 'Escape') {
                    clearPropertySearch(this);
                }
            });

            // Search button functionality
            if (searchButton) {
                searchButton.addEventListener('click', function() {
                    performPropertySearch(searchInput);
                });
            }
            
            function performPropertySearch(searchInput) {
                const searchTerm = searchInput.value.toLowerCase().trim();
                const container = document.getElementById('property-stats-container');
                const items = Array.from(container.getElementsByClassName('property-stat-row'));
                
                let visibleCount = 0;
                let totalCount = items.length;
                
                // Filter items based on search term
                items.forEach(function(item) {
                    const propertyNameElement = item.querySelector('.badge-custom');
                    if (propertyNameElement) {
                        const propertyName = propertyNameElement.textContent.toLowerCase();
                        
                        if (searchTerm === '' || propertyName.includes(searchTerm)) {
                            item.setAttribute('data-search-visible', 'true');
                            visibleCount++;
                        } else {
                            item.setAttribute('data-search-visible', 'false');
                        }
                    }
                });
                
                // Update search results count
                updatePropertySearchResults(visibleCount, totalCount, searchTerm);
                
                // Re-initialize pagination and go to first page
                initPagination('property-stats-container', 'property-stat-row', 'stats-pagination', 'stats-page-size');
                
                // Always go to page 1 after search
                const currentPageSize = document.getElementById('stats-page-size') ? 
                    parseInt(document.getElementById('stats-page-size').value) : 10;
                goToPage(1, 'property-stats-container', 'property-stat-row', currentPageSize, 'stats-pagination');
            }
            
            function clearPropertySearch(searchInput) {
                searchInput.value = '';
                performPropertySearch(searchInput);
                searchInput.focus();
            }
            
            function updatePropertySearchResults(visibleCount, totalCount, searchTerm) {
                const resultsElement = document.getElementById('property-search-results');
                
                if (resultsElement) {
                    if (searchTerm === '') {
                        resultsElement.innerHTML = `<span class="text-muted">Showing all ${totalCount} properties - Type and click <i class="bi bi-search"></i> or press Enter to search</span>`;
                    } else if (visibleCount === 0) {
                        resultsElement.innerHTML = `<span class="text-danger">No properties found for "${searchTerm}"</span>`;
                    } else if (visibleCount === totalCount) {
                        resultsElement.innerHTML = `<span class="text-success">All ${totalCount} properties match "${searchTerm}"</span>`;
                    } else {
                        resultsElement.innerHTML = `<span class="text-info">Found ${visibleCount} of ${totalCount} properties for "${searchTerm}"</span>`;
                    }
                }
            }
        }
        
        // Global pagination and navigation functions
        function goToPage(pageNumber, containerId, itemClass, itemsPerPage, paginationId) {
            const container = document.getElementById(containerId);
            const allItems = Array.from(container.getElementsByClassName(itemClass));
            const paginationElement = document.getElementById(paginationId);
            
            // Get items that should be visible based on search filter
            const filteredItems = allItems.filter(item => {
                const searchVisible = item.getAttribute('data-search-visible');
                const shouldShow = searchVisible === null || searchVisible === 'true';
                return shouldShow;
            });
            
            // Update pagination active state
            if (paginationElement) {
                const pageItems = paginationElement.getElementsByClassName('page-item');
                for (let i = 0; i < pageItems.length; i++) {
                    if (pageItems[i].textContent.trim() === pageNumber.toString()) {
                        pageItems[i].className = 'page-item active';
                    } else if (pageItems[i].textContent.trim() !== '«' && pageItems[i].textContent.trim() !== '»') {
                        pageItems[i].className = 'page-item';
                    }
                }
            }
            
            // Hide all items first
            allItems.forEach((item, index) => {
                item.style.display = 'none';
            });
            
            // Show items for current page (only from filtered items)
            const startIndex = (pageNumber - 1) * itemsPerPage;
            const endIndex = Math.min(startIndex + itemsPerPage, filteredItems.length);
            
            for (let i = startIndex; i < endIndex; i++) {
                if (filteredItems[i]) {
                    filteredItems[i].style.display = '';
                }
            }
        }
        
        function initPagination(containerId, itemClass, paginationId, pageSizeSelectId) {
            const container = document.getElementById(containerId);
            const pageSizeSelect = document.getElementById(pageSizeSelectId);
            if (!container) return;
            
            // Remove existing event listener to prevent duplicate bindings
            if (pageSizeSelect && !pageSizeSelect.hasAttribute('data-listener-bound')) {
                pageSizeSelect.addEventListener('change', function() {
                    const newItemsPerPage = parseInt(this.value);
                    renderPagination();
                    goToPage(1, containerId, itemClass, newItemsPerPage, paginationId);
                });
                // Mark as having listener bound
                pageSizeSelect.setAttribute('data-listener-bound', 'true');
            }
            
            function renderPagination() {
                const allItems = Array.from(container.getElementsByClassName(itemClass));
                
                // Always get current page size from select element
                const currentPageSizeSelect = document.getElementById(pageSizeSelectId);
                const currentItemsPerPage = currentPageSizeSelect ? parseInt(currentPageSizeSelect.value) : 10;
                
                // Use same filtering logic as goToPage function
                const filteredItems = allItems.filter(item => {
                    const searchVisible = item.getAttribute('data-search-visible');
                    // If no search filter is applied, show all items
                    return searchVisible === null || searchVisible === 'true';
                });
                
                const totalItems = filteredItems.length;
                const totalPages = Math.max(1, Math.ceil(totalItems / currentItemsPerPage));
                
                // Create pagination
                const paginationElement = document.getElementById(paginationId);
                if (!paginationElement) return;
                
                // Clear pagination
                paginationElement.innerHTML = '';
                
                // Don't show pagination if there's only one page or no items
                if (totalPages <= 1) {
                    // Hide the entire pagination container when not needed
                    const paginationContainer = paginationElement.closest('.pagination-container');
                    if (paginationContainer) {
                        paginationContainer.style.display = 'none';
                    }
                    return;
                }
                
                // Show the pagination container when needed
                const paginationContainer = paginationElement.closest('.pagination-container');
                if (paginationContainer) {
                    paginationContainer.style.display = '';
                }
                
                // Previous button
                const prevLi = document.createElement('li');
                prevLi.className = 'page-item disabled';
                prevLi.innerHTML = '<a class="page-link" href="#" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a>';
                paginationElement.appendChild(prevLi);
                
                // Add page numbers
                for (let i = 1; i <= totalPages; i++) {
                    const pageLi = document.createElement('li');
                    pageLi.className = i === 1 ? 'page-item active' : 'page-item';
                    pageLi.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                    pageLi.addEventListener('click', function(e) {
                        e.preventDefault();
                        goToPage(i, containerId, itemClass, currentItemsPerPage, paginationId);
                    });
                    paginationElement.appendChild(pageLi);
                }
                
                // Next button
                const nextLi = document.createElement('li');
                nextLi.className = totalPages <= 1 ? 'page-item disabled' : 'page-item';
                nextLi.innerHTML = '<a class="page-link" href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a>';
                paginationElement.appendChild(nextLi);
                
                // Add event listeners to prev/next buttons
                if (paginationElement.firstChild) {
                    paginationElement.firstChild.addEventListener('click', function(e) {
                        e.preventDefault();
                        const activePage = paginationElement.querySelector('.active');
                        if (activePage && activePage.previousElementSibling && activePage.previousElementSibling.previousElementSibling) {
                            const pageNum = parseInt(activePage.textContent) - 1;
                            if (pageNum >= 1) {
                                goToPage(pageNum, containerId, itemClass, currentItemsPerPage, paginationId);
                            }
                        }
                    });
                }
                
                if (paginationElement.lastChild) {
                    paginationElement.lastChild.addEventListener('click', function(e) {
                        e.preventDefault();
                        const activePage = paginationElement.querySelector('.active');
                        if (activePage && activePage.nextElementSibling && activePage.nextElementSibling.nextElementSibling) {
                            const pageNum = parseInt(activePage.textContent) + 1;
                            if (pageNum <= totalPages) {
                                goToPage(pageNum, containerId, itemClass, currentItemsPerPage, paginationId);
                            }
                        }
                    });
                }
            }
            
            // Initial render
            renderPagination();
            // Always call goToPage to ensure items are displayed correctly, even if no pagination is shown
            const currentItemsPerPage = pageSizeSelect ? parseInt(pageSizeSelect.value) : 10;
            goToPage(1, containerId, itemClass, currentItemsPerPage, paginationId);
        }

        // Activities table searching function
        function initActivitiesSearching() {
            const searchInput = document.getElementById('activities-search');
            const searchButton = document.getElementById('activities-search-btn');

            if (!searchInput) return;

            // Search on Enter key and clear on Escape
            searchInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    performActivitiesSearch(this);
                } else if (e.key === 'Escape') {
                    clearActivitiesSearch(this);
                }
            });

            // Search button functionality
            if (searchButton) {
                searchButton.addEventListener('click', function() {
                    performActivitiesSearch(searchInput);
                });
            }

            function performActivitiesSearch(searchInput) {
                const searchTerm = searchInput.value.toLowerCase().trim();
                const container = document.getElementById('activities-container');
                const rows = container.querySelectorAll('.activity-row');
                const resultsCount = document.getElementById('activities-search-results');

                let visibleCount = 0;

                rows.forEach(function(row) {
                    const activityName = row.querySelector('.activity-name').textContent.toLowerCase();

                    // If no search term, show all rows
                    if (!searchTerm) {
                        row.removeAttribute('data-search-visible');
                        visibleCount++;
                    } else {
                        const matches = activityName.includes(searchTerm);
                        if (matches) {
                            row.setAttribute('data-search-visible', 'true');
                            visibleCount++;
                        } else {
                            row.setAttribute('data-search-visible', 'false');
                        }
                    }
                });

                console.log('Search performed:', {searchTerm, visibleCount, totalRows: rows.length});

                // Update results count
                if (resultsCount) {
                    if (searchTerm) {
                        resultsCount.textContent = `Found ${visibleCount} of ${rows.length} activities`;
                    } else {
                        resultsCount.textContent = '';
                    }
                }

                // Immediately show/hide rows based on search before pagination update
                rows.forEach(function(row) {
                    const searchVisible = row.getAttribute('data-search-visible');
                    if (searchVisible === null || searchVisible === 'true') {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });

                console.log('Rows visibility updated, calling pagination update...');

                // Update pagination after search
                updateActivitiesPagination();
            }

            function clearActivitiesSearch(searchInput) {
                searchInput.value = '';
                performActivitiesSearch(searchInput);
                searchInput.focus();
            }
        }

        // Initialize Activities page size selector
        function initActivitiesPageSize() {
            const pageSizeSelect = document.getElementById('activities-page-size');

            if (!pageSizeSelect) return;

            // Remove existing event listener to prevent duplicate bindings
            if (!pageSizeSelect.hasAttribute('data-activities-listener-bound')) {
                pageSizeSelect.addEventListener('change', function() {
                    console.log('Activities page size changed to:', this.value);
                    updateActivitiesPagination();
                });
                // Mark as having listener bound
                pageSizeSelect.setAttribute('data-activities-listener-bound', 'true');
            }
        }

        // Activities table sorting function
        function initActivitiesSorting() {
            const sortIcon = document.getElementById('visit-count-sort');

            if (!sortIcon) return;

            sortIcon.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();

                console.log('Sort icon clicked, current order:', this.dataset.order);

                const currentOrder = this.dataset.order || 'none';
                const container = document.getElementById('activities-container');
                const rows = Array.from(container.querySelectorAll('.activity-row'));

                console.log('Found rows:', rows.length);

                // Reset only activities sort icons (not property stats sort icons)
                document.querySelectorAll('.activities-sort-icon').forEach(icon => {
                    if (icon !== this) {
                        icon.className = 'bi bi-arrow-down-up text-muted sort-icon activities-sort-icon';
                        icon.dataset.order = 'none';
                    }
                });

                let newOrder;
                if (currentOrder === 'none' || currentOrder === 'desc') {
                    newOrder = 'asc';
                    this.className = 'bi bi-arrow-up text-primary sort-icon activities-sort-icon';
                } else {
                    newOrder = 'desc';
                    this.className = 'bi bi-arrow-down text-primary sort-icon activities-sort-icon';
                }

                this.dataset.order = newOrder;
                console.log('New order set to:', newOrder);

                // Sort rows
                rows.sort((a, b) => {
                    const aCount = parseInt(a.dataset.visitCount) || 0;
                    const bCount = parseInt(b.dataset.visitCount) || 0;

                    if (newOrder === 'asc') {
                        return aCount - bCount;
                    } else {
                        return bCount - aCount;
                    }
                });

                // Clear container and re-append sorted rows
                container.innerHTML = '';
                rows.forEach(row => container.appendChild(row));

                console.log('Sorting completed');

                // Properly update pagination after sorting
                updateActivitiesPagination();
            });
        }

        // Function to update Activities pagination after sorting
        function updateActivitiesPagination() {
            const container = document.getElementById('activities-container');
            const pageSizeSelect = document.getElementById('activities-page-size');
            const paginationElement = document.getElementById('activities-pagination');

            if (!container || !paginationElement) return;

            const allRows = Array.from(container.querySelectorAll('.activity-row'));
            const itemsPerPage = pageSizeSelect ? parseInt(pageSizeSelect.value) : 10;

            // Filter visible rows (considering search)
            const visibleRows = allRows.filter(row => {
                const searchVisible = row.getAttribute('data-search-visible');
                return searchVisible === null || searchVisible === 'true';
            });

            const totalItems = visibleRows.length;
            const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage));

            console.log('Updating pagination:', {totalItems, itemsPerPage, totalPages});

            // Clear pagination
            paginationElement.innerHTML = '';

            // Find pagination container
            const paginationContainer = paginationElement.closest('.d-flex');

            // Don't show pagination if there's only one page or no items
            if (totalPages <= 1) {
                if (paginationContainer) {
                    paginationContainer.style.display = 'none';
                }
                // Show visible rows and hide invisible rows
                allRows.forEach(row => {
                    const searchVisible = row.getAttribute('data-search-visible');
                    if (searchVisible === null || searchVisible === 'true') {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
                return;
            }

            // Show the pagination container when needed
            if (paginationContainer) {
                paginationContainer.style.display = '';
            }

            // Create Previous button
            const prevLi = document.createElement('li');
            prevLi.className = 'page-item';
            prevLi.id = 'activities-prev-page';

            const prevA = document.createElement('a');
            prevA.className = 'page-link';
            prevA.href = '#';
            prevA.innerHTML = '&laquo;';
            prevA.addEventListener('click', function(e) {
                e.preventDefault();
                const currentPage = getCurrentActivitiesPage();
                if (currentPage > 1) {
                    goToActivitiesPage(currentPage - 1, totalPages, itemsPerPage);
                }
            });

            prevLi.appendChild(prevA);
            paginationElement.appendChild(prevLi);

            // Create page number buttons
            for (let i = 1; i <= totalPages; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === 1 ? 'active' : ''}`;
                li.setAttribute('data-page', i);

                const a = document.createElement('a');
                a.className = 'page-link';
                a.href = '#';
                a.textContent = i;
                a.addEventListener('click', function(e) {
                    e.preventDefault();
                    goToActivitiesPage(i, totalPages, itemsPerPage);
                });

                li.appendChild(a);
                paginationElement.appendChild(li);
            }

            // Create Next button
            const nextLi = document.createElement('li');
            nextLi.className = 'page-item';
            nextLi.id = 'activities-next-page';

            const nextA = document.createElement('a');
            nextA.className = 'page-link';
            nextA.href = '#';
            nextA.innerHTML = '&raquo;';
            nextA.addEventListener('click', function(e) {
                e.preventDefault();
                const currentPage = getCurrentActivitiesPage();
                if (currentPage < totalPages) {
                    goToActivitiesPage(currentPage + 1, totalPages, itemsPerPage);
                }
            });

            nextLi.appendChild(nextA);
            paginationElement.appendChild(nextLi);

            // Show first page and update navigation buttons
            goToActivitiesPage(1, totalPages, itemsPerPage);
        }

        // Function to navigate to specific page in Activities table
        function goToActivitiesPage(pageNumber, totalPages, itemsPerPage) {
            const container = document.getElementById('activities-container');
            const paginationElement = document.getElementById('activities-pagination');

            if (!container) return;

            const allRows = Array.from(container.querySelectorAll('.activity-row'));

            // Filter visible rows (considering search)
            const visibleRows = allRows.filter(row => {
                const searchVisible = row.getAttribute('data-search-visible');
                return searchVisible === null || searchVisible === 'true';
            });

            const startIndex = (pageNumber - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;

            console.log('Going to page:', {pageNumber, startIndex, endIndex, totalVisible: visibleRows.length});

            // Hide all rows first
            allRows.forEach(row => {
                row.style.display = 'none';
            });

            // Show rows for current page
            visibleRows.forEach((row, index) => {
                if (index >= startIndex && index < endIndex) {
                    row.style.display = '';
                }
            });

            // Update pagination active state
            if (paginationElement) {
                // Update page number buttons
                const pageItems = paginationElement.querySelectorAll('.page-item[data-page]');
                pageItems.forEach((item) => {
                    const page = parseInt(item.getAttribute('data-page'));
                    if (page === pageNumber) {
                        item.classList.add('active');
                    } else {
                        item.classList.remove('active');
                    }
                });

                // Update Previous button state
                const prevButton = paginationElement.querySelector('#activities-prev-page');
                if (prevButton) {
                    if (pageNumber <= 1) {
                        prevButton.classList.add('disabled');
                    } else {
                        prevButton.classList.remove('disabled');
                    }
                }

                // Update Next button state
                const nextButton = paginationElement.querySelector('#activities-next-page');
                if (nextButton) {
                    if (pageNumber >= totalPages) {
                        nextButton.classList.add('disabled');
                    } else {
                        nextButton.classList.remove('disabled');
                    }
                }
            }
        }

        // Function to get current active page in Activities pagination
        function getCurrentActivitiesPage() {
            const paginationElement = document.getElementById('activities-pagination');
            if (!paginationElement) return 1;

            const activeItem = paginationElement.querySelector('.page-item.active[data-page]');
            if (activeItem) {
                return parseInt(activeItem.getAttribute('data-page'));
            }
            return 1;
        }

        // Function to scroll to screenshot by ID
        function scrollToScreenshot(screenshotId) {
            const screenshotElement = document.getElementById(screenshotId);
            if (screenshotElement) {
                // Scroll to the screenshot with smooth behavior
                screenshotElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });

                // Add a highlight effect
                screenshotElement.style.border = '3px solid #007bff';
                screenshotElement.style.borderRadius = '8px';
                screenshotElement.style.transition = 'border 0.3s ease';

                // Remove highlight after 3 seconds
                setTimeout(() => {
                    screenshotElement.style.border = '';
                    screenshotElement.style.borderRadius = '';
                }, 3000);
            } else {
                console.warn('Screenshot with ID', screenshotId, 'not found');
            }
        }
    </script>
</body>
</html> 
